<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>用户管理</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row class="pd20 mt20">
      <a-col :span="6">
        角色名：
        <a-input placeholder="请输入" v-model="queryForm.roleName" />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="getList"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="cleanQuery">重置</a-button>
      </a-col>
    </a-row>
    <a-row class="pd20 mt20">
      <div class="btn_box">
        <div>角色列表</div>
        <a-button type="primary" @click="addFn" v-hasPermi="['role:add']"
          >添加</a-button
        >
      </div>
      <a-spin :spinning="loading">
        <a-table
          :scroll="{ x: 500 }"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
        >
          <a slot="name" slot-scope="text">{{ text }}</a>
          <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
          <span slot="action" slot-scope="text, record">
            <!-- <a @click="deptFn(text,record)">关联部门</a>
            <a-divider type="vertical" /> -->
            <a @click="menuFn(text, record)" v-hasPermi="['role:right']"
              >权限配置</a
            >
            <a-divider type="vertical" />
            <a @click="editFn(text, record)" v-hasPermi="['role:edit']">修改</a>
            <a-divider type="vertical" />
            <a
              @click="delFn(text, record)"
              class="red"
              v-hasPermi="['role:del']"
              >删除</a
            >
          </span>
        </a-table>
        <div class="page_box">
          <a-pagination
            v-model="queryForm.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total"
            show-size-changer
            :page-size="queryForm.current"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            :show-total="(total) => `共 ${total} 条`"
          ></a-pagination>
        </div>
      </a-spin>
    </a-row>
    <a-modal
      title="角色配置"
      :visible="dialogVisible"
      width="38%"
      ok-text="确认"
      cancel-text="取消"
      @cancel="dialogVisible = false"
      @ok="putDict"
    >
      <a-spin :spinning="loading2">
        <div v-if="type == 'Create'">
          <a-form :form="form">
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="角色名称"
            >
              <a-input
                v-decorator="[
                  'roleName',
                  { rules: [{ required: true, message: '请输入角色名称' }] },
                ]"
                placeholder="请输入角色名称"
              />
            </a-form-item>
            <!-- <a-form-item :label-col="formItemLayout.labelCol"
                     :wrapper-col="formItemLayout.wrapperCol"
                     label="字典类型">
          <a-input v-decorator="['dictType', { rules: [{ required: true, message: '请输入字典类型' }] }]"
                   placeholder="请输入字典类型" />
        </a-form-item> -->
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="排序"
            >
              <a-input-number
                v-decorator="[
                  'roleSort',
                  { rules: [{ required: true, message: '请输入排序' }] },
                ]"
                placeholder="请输入排序"
              />
            </a-form-item>
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="备注"
            >
              <a-input v-decorator="['remark']" placeholder="请输入备注" />
            </a-form-item>
          </a-form>
        </div>
        <div v-if="type == 'Dept'">
          <a-form :form="form">
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="选择部门"
            >
              <a-tree-select
                v-decorator="[
                  'deptId',
                  { rules: [{ required: true, message: '请选择岗位' }] },
                ]"
                show-search
                style="width: 100%"
                @change="changeDept"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择部门"
                allow-clear
                tree-default-expand-all
                :treeData="deptList"
                :replaceFields="{
                  title: 'deptName',
                  children: 'childList',
                  value: 'id',
                }"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="选择岗位"
            >
              <a-select
                style="width: 120px"
                v-decorator="[
                  'postId',
                  { rules: [{ required: true, message: '请选择岗位' }] },
                ]"
                placeholder="请选择岗位"
              >
                <a-select-option
                  v-for="(item, index) in postList"
                  :key="index"
                  :value="item.postId"
                >
                  {{ item.postName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div v-if="type == 'Menu'">
          <a-form :form="form">
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="配置路由权限"
            >
              <a-tree
                :checkedKeys="checkedKeys"
                checkable
                ref="treeRef"
                checkStrictly
                :expanded-keys="expandedKeys"
                :selected-keys="selectedKeys"
                :tree-data="menuList"
                default_expand_all
                @check="changeMenu"
                @expand="onExpand"
                @onCheck="onCheck"
                placeholder="请配置路由权限"
                :replaceFields="{
                  title: 'menuName',
                  children: 'childList',
                  key: 'id',
                }"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { Modal } from "ant-design-vue";
import { message } from "ant-design-vue";
export default {
  data() {
    return {
      loading: true,
      loading2: false,
      dialogVisible: false,
      queryForm: { current: 20, offset: 1 },
      total: 0,
      form: this.$form.createForm(this, { name: "coordinated" }),
      id: null,
      type: "Create",
      deptId: null,
      roleId: null,
      tableData: [],
      deptList: [],
      postList: [],
      menuList: [],
      expandedKeys: [],
      selectedKeys: [],
      checkedKeys: [],
      lastSelectedId: "",
      defaultExpandAll: true,
      ids: [],
      columns: [
        {
          title: "角色名称",
          dataIndex: "roleName",
          key: "roleName",
        },
        {
          title: "顺序",
          dataIndex: "roleSort",
          key: "roleSort",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
        },
      ],
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      children: [],
    };
  },
  watch: {
    checkedKeys(val) {
      if (val.length > 0) {
        // console.log('onCheck1111', val)
      }
    },
  },
  mounted() {
    this.getList();
    this.getDeptList();
    this.getMenuList();
  },
  methods: {
    onExpand(expandedKeys) {
      console.log("onExpand", expandedKeys);
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    getList() {
      this.loading = true;
      const url = "/government-platform-center/role";
      const params = this.queryForm;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData = res.data.data;
            this.total = res.data.total;
            this.loading = false;
          }
        });
    },
    cleanQuery() {
      this.queryForm = {};
      this.getList();
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.current = pageSize;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    delFn(text, record) {
      console.log(text, record);
      const that = this;
      Modal.confirm({
        title: "确认删除",
        content: "您确定要删除这项内容吗？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const url = `/government-platform-center/role/deleteById?id=${text.roleId}`;
          that.$axios.post(url).then((res) => {
            if (res.data.code == 0) {
              that.getList();
              message.success("操作成功");
            }
          });
        },
        onCancel() {
          // 在此处理取消逻辑
          console.log("删除已取消");
        },
      });
    },
    deptFn(text, record) {
      this.type = "Dept";
      this.roleId = text.roleId;
      this.dialogVisible = true;
      this.form.resetFields();
    },
    addFn() {
      this.loading2 = false;
      this.type = "Create";
      this.dialogVisible = true;
      this.id = null;
      this.form.resetFields();
    },
    editFn(text, record) {
      this.loading2 = true;
      this.type = "Create";
      this.dialogVisible = true;
      const url = `/government-platform-center/role/${text.roleId}`;
      const params = this.queryForm;
      this.id = text.roleId;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.form.setFieldsValue(res.data.data);
            this.id = res.data.data.roleId;
            this.loading2 = false;
          }
        });
    },
    putDict() {
      this.loading2 = true;
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        }
        if (this.type == "Create") {
          if (!this.id) {
            const url = "/government-platform-center/role";
            this.$axios
              .post(url, values, {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              })
              .then((res) => {
                if (res.data.code == 0) {
                  this.getList();
                  this.dialogVisible = false;
                  message.success("操作成功");
                  this.loading2 = false;
                }
              });
          } else {
            const form = { ...values, roleId: this.id };
            const url = "/government-platform-center/role/edit";
            this.$axios
              .post(url, form, {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              })
              .then((res) => {
                if (res.data.code == 0) {
                  this.getList();
                  this.dialogVisible = false;
                  this.loading2 = false;
                  message.success("操作成功");
                }
              });
          }
        } else if (this.type == "Dept") {
          const url = "/government-platform-center/roleDept";
          const form = {
            deptId: values.deptId,
            postId: values.postId,
            roleId: this.roleId,
          };
          console.log(form, "form");
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.dialogVisible = false;
                this.loading2 = false;
                message.success("操作成功");
              }
            });
        } else if (this.type == "Menu") {
          const url = "/government-platform-center/roleMenu";
          console.log(this.checkedKeys);
          const form = {
            menuIds: this.checkedKeys.join(","),
            roleId: this.roleId,
          };
          this.$axios
            .post(url, form, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.getList();
                this.dialogVisible = false;
                this.loading2 = false;
                message.success("操作成功");
              }
            });
        }
      });
    },
    // 关联部门模块
    menuFn(text, record) {
      this.loading2 = true;
      this.type = "Menu";
      this.roleId = text.roleId;
      this.checkedKeys = [];
      this.dialogVisible = true;
      this.form.resetFields();
      const url = "/government-platform-center/roleMenu";
      const params = { roleId: this.roleId };
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.ids = [];
            this.getIds(res.data.data);
            this.checkedKeys = this.ids;
            setTimeout(() => {
              this.loading2 = false;
            }, 1);
          }
        });
    },
    getIds(list) {
      list.forEach((item) => {
        this.ids.push(item.id);
        if (item.childList && item.childList.length) {
          this.getIds(item.childList);
        }
      });
    },
    changeDept(e) {
      this.deptId = e;
      this.getPostList();
    },
    // 部门列表
    getDeptList() {
      const url = "/government-platform-center/dept";
      const params = this.queryForm;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.deptList = res.data.data;
            this.getOther(this.deptList);
          }
        });
    },
    getOther(list) {
      list.forEach((item, index) => {
        item = { ...item, ...item.thisData };
        // item['']
        this.$set(list, index, item);
        if (item.childList && item.childList.length > 0) {
          this.getOther(item.childList);
        }
      });
    },
    //岗位列表
    getPostList() {
      const url = "/government-platform-center/post";
      const params = { current: 999, offset: 1, deptId: this.deptId };
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.postList = res.data.data;
          }
        });
    },
    //点击菜单配置权限
    async changeMenu(selectedKeys, info) {
      this.checkedKeys = selectedKeys.checked;
      this.lastSelectedId = this.checkedKeys[this.checkedKeys.length - 1];
      await this.getLastSelectedIdChildren(this.menuList, this.lastSelectedId);
      this.addCheckedKeys(this.children);
      console.log(this.children);
    },
    // 获取最后一个点击的子集
    getLastSelectedIdChildren(list, id) {
      list.forEach((item) => {
        if (item.id == id) {
          this.children = item.childList;
        } else if (item.childList && item.childList.length > 0) {
          this.getLastSelectedIdChildren(item.childList, id);
        }
      });
    },
    //
    addCheckedKeys(list) {
      list.forEach((item) => {
        this.checkedKeys.push(item.id);
        if (item.childList && item.childList.length > 0) {
          this.addCheckedKeys(item.childList);
        }
      });
    },
    onCheck(checkedKeys, info) {
      console.log("onCheck2", checkedKeys, info);
    },
    getMenuList() {
      const url = "/government-platform-center/menu";
      const params = this.queryForm;
      this.$axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.menuList = res.data.data;
            this.getMenuOther(this.menuList);
          }
        });
    },
    getMenuOther(list) {
      list.forEach((item, index) => {
        item = { ...item, ...item.thisData };
        if (item.isHideen == 0) {
          item["isHiddenName"] = "隐藏";
        }
        if (item.isHideen == 1) {
          item["isHiddenName"] = "显示";
        }
        this.$set(list, index, item);
        if (item.childList && item.childList.length > 0) {
          this.getOther(item.childList);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.ant-row {
  border-radius: 5px;

  background: #fff;
  color: #000;
}

v-deep {
  .ant-table-thead > tr > th {
    color: #000;
    font-weight: bold;
  }
  .ant-table-tbody > tr > td {
    color: #000;
  }
  .el-table thead {
    color: black;
    font-weight: bold;
    background: #fafafa;
  }
  .el-table th.el-table__cell {
    background: #fafafa;
  }
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

@media screen and (max-width: 1300px) {
  .el-input {
    width: 70%;
  }

  .el-select {
    width: 70%;
  }

  .app {
    width: calc(100% - 50px);
  }
}

@media screen and (max-width: 1100px) {
  .el-input {
    width: 90%;
  }

  .el-select {
    width: 90%;
  }
}
</style>
